package com.example.administrator.newxlmedical;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import adapters.CardinalNumberAdapter;
import adapters.SearchAdapter;
import beans.GoodsDetailInfoBean;
import beans.ItemEntity;
import beans.StorageWarningInfoBean;
import beans.TimeoutBean;
import beans.WarningInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import dialogs.GoodsDetialsDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utils.ActivityUtil;
import utils.CardinalNumberSortUtils;
import utils.DefaultFuzzySearchRule;
import utils.FuzzySearchUtils;
import utils.ScreenUtils;
import utils.ViewUtil;

public class CardinalNumberActivity extends BaseActivity {
    @BindView(R.id.et_cardinal_number_name)
    EditText etName;
    @BindView(R.id.tv_cardinal_number_search)
    TextView tvSearch;
    @BindView(R.id.tv_cardinal_number_goods)
    TextView tvGoods;
    @BindView(R.id.iv_warn_set_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_cardinal_number_goods_sort)
    RelativeLayout rlGoodsSort;
    @BindView(R.id.tv_cardinal_number_size)
    TextView tvSpecification;
    @BindView(R.id.iv_warn_set_specification_sort)
    ImageView ivSpecificationSort;
    @BindView(R.id.rl_cardinal_number_specification_sort)
    RelativeLayout rlSpecificationSort;
    @BindView(R.id.tv_cardinal_number_supplier)
    TextView tvSupplier;
    @BindView(R.id.iv_warn_set_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_cardinal_number_supplier_sort)
    RelativeLayout rlSupplierSort;
    @BindView(R.id.tv_cardinal_number_count)
    TextView tvCount;
    @BindView(R.id.iv_warn_set_number_sort)
    ImageView ivNumberSort;
    @BindView(R.id.rl_cardinal_number_number_sort)
    RelativeLayout rlNumberSort;
    @BindView(R.id.rv_cardinal_number_activity)
    RecyclerView recyclerView;
    @BindView(R.id.fl_cardinal_number_empty)
    FrameLayout flEmpty;
    @BindView(R.id.iv_cardinal_number_home)
    ImageView ivHome;

    private List<WarningInfoBean.DataBean> list = new ArrayList<>();
    private List<WarningInfoBean.DataBean> allList = new ArrayList<>();
    private List<WarningInfoBean.DataBean> fuzzyList = new ArrayList<>();
    private List<WarningInfoBean.DataBean> sortList = new ArrayList<>();
    private CardinalNumberAdapter adapter;
    private DefaultFuzzySearchRule mIFuzzySearchRule;
    private FuzzySearchFilter fuzzySearchFilter;
    private int fuzzyPosition = 1;
    private String[] split1;
    private int count;
    private boolean isSortGoods, isSortSpecification, isSortSupplier, isSortNumber;
    private int sortGoods, sortSpecification, sortSupplier, sortNumber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cardinal_number);
        ButterKnife.bind(this);

        getData();
    }

    @Override
    public void initView() {
        super.initView();
        mIFuzzySearchRule = new DefaultFuzzySearchRule();
        fuzzySearchFilter = new FuzzySearchFilter();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        adapter = new CardinalNumberAdapter(this, list);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void setListener() {
        super.setListener();

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                WarningInfoBean.DataBean bean = list.get(position);

                String name = bean.getGoodName();
                String specification = "规格  :  " + bean.getSpecification();
                String supplier = "供应商  :  " + bean.getManufacturer();
                String count = "单位  :  " + bean.getGoodsUnit();
                String operator = "基数  :  " + bean.getCardinalNumber();
                String time = "预警  :  " + bean.getWarnCount();

                String[] content = {name, specification, supplier, count, operator, "", "", ""};
                GoodsDetialsDialog dialog = new GoodsDetialsDialog(CardinalNumberActivity.this, R.style.dialog, content);

                dialog.show();
            }
        });

        // 点击键盘搜索按钮
        etName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
//                    sort(0);
                    search();
                    return true;
                }
                return false;
            }
        });
    }

    // 获取柜子中的物品
    private void getData() {
        list.clear();
        allList.clear();
        fuzzyList.clear();
        sortList.clear();
        showLoadingView(flEmpty);
        GetRetrofit.getInstance().getCaidinalNumberAllGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode)
                .enqueue(new Callback<WarningInfoBean>() {
                    @Override
                    public void onResponse(Call<WarningInfoBean> call, Response<WarningInfoBean> response) {
                        hideLoadingView();
                        WarningInfoBean body = response.body();
                        if (body != null && body.getData() != null && body.getData().size() != 0) {
                            list.addAll(body.getData());
                            allList.addAll(body.getData());
                            fuzzyList.addAll(body.getData());
                            sortList.addAll(body.getData());
                            CardinalNumberSortUtils.sortCardinalNumberGoods(list, true);
                            adapter.notifyDataSetChanged();
                        } else {
                            showEmptyView(flEmpty);
                        }
                    }

                    @Override
                    public void onFailure(Call<WarningInfoBean> call, Throwable t) {
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }
                });
    }


    @OnClick({R.id.iv_cardinal_number_home,R.id.tv_cardinal_number_search,R.id.rl_cardinal_number_goods_sort,R.id.rl_cardinal_number_specification_sort,
            R.id.rl_cardinal_number_supplier_sort,R.id.rl_cardinal_number_number_sort})
    public void onViewClicked(View view) {
        switch (view.getId()){

            case R.id.iv_cardinal_number_home:
                ActivityUtil.jumpToActivity(this,MainActivity.class);
                finish();
                break;

            case R.id.tv_cardinal_number_search:
                search();
                break;

            case R.id.rl_cardinal_number_goods_sort:
                sort(1);
                break;
            case R.id.rl_cardinal_number_specification_sort:
                sort(3);
                break;
            case R.id.rl_cardinal_number_supplier_sort:
                sort(2);
                break;
            case R.id.rl_cardinal_number_number_sort:
                sort(4);
                break;
        }
    }

    private void search() {
        hideEmptyView();
        sort(0);
        ScreenUtils.closeKeybord(etName, CardinalNumberActivity.this);
        String name = etName.getText().toString();
        if (TextUtils.isEmpty(name)){
            getData();
        }else {
            split1 = name.split(" ");
            fuzzySearchFilter.filter(split1[count]);
        }
    }

    private class FuzzySearchFilter extends Filter {

        /**
         * 执行过滤操作,如果搜索的关键字为空，默认所有结果
         */

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            List<ItemEntity> dateList = FuzzySearchUtils.fillCaridnalNumberData(fuzzyList,fuzzyPosition);
            FilterResults result = new FilterResults();
            List<ItemEntity> filterList = new ArrayList<>();
            for (ItemEntity item : dateList) {
                if (mIFuzzySearchRule.accept(constraint, item.getSourceKey(), item.getFuzzyKey())) {
                    filterList.add(item);
                }
            }
            result.values = filterList;
            result.count = filterList.size();
            return result;
        }

        /**
         * 得到过滤结果
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            fuzzyList.clear();
            List<ItemEntity> mDataList = (List<ItemEntity>) results.values;
            if (mDataList != null && mDataList.size() != 0) {
                for (int i = 0; i < mDataList.size(); i++) {
                    ItemEntity itemEntity = mDataList.get(i);
                    fuzzyList.add(itemEntity.getmWarnBean());
                }
            }
            sendEmptyMessage(HandlerConstant.FUZZY_SEARCH);
        }
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what){
            case HandlerConstant.FUZZY_SEARCH:
                count++;
                if (count == split1.length) {
                    count = 0;
                    list.clear();
                    sortList.clear();
                    list.addAll(fuzzyList);
                    sortList.addAll(fuzzyList);
                    if (list.size() == 0) {
                        showEmptyView(flEmpty);
                    }
                    adapter.notifyDataSetChanged();
                    hideLoadingView();
                    // 重置模糊搜索
                    fuzzyPosition = 1;
                    fuzzyList.clear();
                    fuzzyList.addAll(allList);
                }else {
                    fuzzyPosition = 2;
                    fuzzySearchFilter.filter(split1[count]);
                }
                break;
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                CardinalNumberSortUtils.sortCardinalNumberGoods(list, isSortGoods);
            } else {
                clearSortDate();
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                sortSupplier++;
                isSortSupplier = !isSortSupplier;
                CardinalNumberSortUtils.sortCardinalNumberSupplier(list, isSortSupplier);
            } else {
                clearSortDate();
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {
            if (sortSpecification != 2) {
                sortSpecification++;
                isSortSpecification = !isSortSpecification;
                CardinalNumberSortUtils.sortCardinalNumberSpecification(list, isSortSpecification);
            } else {
                clearSortDate();
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        if (type == 4) {
            if (sortNumber != 2) {
                sortNumber++;
                isSortNumber = !isSortNumber;
                CardinalNumberSortUtils.sortCardinalNumberNumber(list, isSortNumber);
            } else {
                clearSortDate();
            }
        } else {
            sortNumber = 0;
            isSortNumber = false;
        }

        ViewUtil.setSortColor(this, tvGoods, ivGoodsSort, sortGoods);
        ViewUtil.setSortColor(this, tvSupplier, ivSupplierSort, sortSupplier);
        ViewUtil.setSortColor(this, tvSpecification, ivSpecificationSort, sortSpecification);
        ViewUtil.setSortColor(this, tvCount, ivNumberSort, sortNumber);

        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        list.clear();
        list.addAll(sortList);
        sortGoods = 0;
        sortSupplier = 0;
        sortSpecification = 0;
        sortNumber = 0;
    }
}
